package com.cosytek.farmmanager.data;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;

/**
 * Created by Happy on 2015/4/19.
 */
public class Task {
    public static final long TASK_DATA_EXPIRED_TIMEOUT = 1000*60*10;

    private String id;
    private String name;
    private String status;
    private String description;

    private String type;
    private int valveCount;
    private int pumpCount;
    private int perBatch;
    private String farmName;
    private int durationInMinutes;

    private int usedTimes;
    private int latestUsedTime;
    private long refreshTime;

    private Task() {

    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getStatus() {
        return status;
    }

    public String getType() {
        return type;
    }

    public int getValveCount() {
        return valveCount;
    }

    public int getPumpCount() {
        return pumpCount;
    }

    public int getDurationInMinutes() {
        return durationInMinutes;
    }

    public int getUsedTimes() {
        return usedTimes;
    }

    public int getLatestUsedTime() {
        return latestUsedTime;
    }

    public static Task createFromJSONObject(JSONObject jsonObject) {
        Task t = new Task();

        if (t.refreshFromJSONObject(jsonObject)) {
            return t;
        }

        return null;
    }

    public boolean refreshFromJSONObject(JSONObject jsonObject) {
        try {
            name = jsonObject.getString("name");
            id = jsonObject.getString("id");
            type = jsonObject.getString("type");
            perBatch = jsonObject.getInt("perbatch");
            status = jsonObject.getString("status");
            durationInMinutes = jsonObject.getInt("duration");
            description = jsonObject.getString("description");
            farmName = jsonObject.getString("farm");
            Calendar c = Calendar.getInstance();
            refreshTime = c.getTimeInMillis();

            return true;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

    public String getDescription() {
        return description;
    }


    public boolean isDataExpired() {
        Calendar c = Calendar.getInstance();
        long now = c.getTimeInMillis();

        if (now - refreshTime > TASK_DATA_EXPIRED_TIMEOUT) {
            return true;
        }

        return false;
    }

    public String getFarmName() {
        return farmName;
    }
}
